import { loginByUsername, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    status: '',
    realName: '',
	roles:[],
    phone: '',
	userId:'',
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_REALNAME: (state, realName) => {
      state.realName = realName
    },
    SET_PHONE: (state, phone) => {
      state.phone = phone
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
	SET_ROLES: (state, roles) => {
	  state.roles = roles
	},
	SET_USERID:(state,userId)=>{
		state.userId=userId
	}
  },

  actions : {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(response => {
          // const data = response.data
          commit('SET_TOKEN', response.token)
          setToken(response.token)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(response => {
          if (!response) {
            reject('error')
          }
          // const data = response.data
          commit('SET_NAME', response.userName)
          commit('SET_AVATAR', response.img)
          commit('SET_REALNAME', response.realName)
          commit('SET_PHONE', response.phone)
		  commit('SET_USERID',response.user.userId)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
